package com.java.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.java.service.ShopOrderService;
import com.java.util.CommonUtil;
import com.java.vo.ShopTransOrder;

/**
 * 订单模块
 */
@Controller
@RequestMapping("/shopOrder")
public class QueryShopOrderController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    ShopOrderService shopOrderService;

    private static final String RETURN_FLAG = "return_flag";

    private static final String RETURN_MSG = "return_msg";

    private String toJsonStr(Object obj) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();

        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));// date类型转换格式
        mapper.setSerializationInclusion(Include.ALWAYS);// 设置为always 序列化时
                                                         // 保留null属性

        return mapper.writeValueAsString(obj).replace(":\"\"", ":\"-\"")// 将空串转换为"-"
                .replace(":null", ":\"-\"");// 将null转换为"-"
    }

    @RequestMapping(value = "/setSend", method = RequestMethod.POST)
    @ResponseBody
    public void setSend(@RequestParam String Jdata, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        CommonUtil.setResponseParams(response);
        HashMap<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            com.alibaba.fastjson.JSONObject json1 = JSON.parseObject(Jdata);
            com.alibaba.fastjson.JSONObject jsonData = JSON.parseObject(json1.get("data").toString());
            Integer id = jsonData.getInteger("id");

            if (id == null) {
                throw new Exception("参数有误");
            }

            if (!shopOrderService.setSend(id)) {
                throw new Exception("保存失败");
            }

            jsonMap.put(RETURN_FLAG, true);
            jsonMap.put(RETURN_MSG, "保存成功");
        } catch (Exception e) {
            jsonMap.put(RETURN_FLAG, false);
            jsonMap.put(RETURN_MSG, e.getMessage());
            logger.error(e.getMessage(), e);
        } finally {
            response.getWriter().println(toJsonStr(jsonMap));
            response.flushBuffer();
        }

    }

    private final int TIME_15_MINUTE = 15 * 60 * 1000;

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public void list(@RequestParam String Jdata, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        CommonUtil.setResponseParams(response);
        HashMap<String, Object> jsonMap = new HashMap<String, Object>();
        try {
            com.alibaba.fastjson.JSONObject json1 = JSON.parseObject(Jdata);
            com.alibaba.fastjson.JSONObject jsonData = JSON.parseObject(json1.get("data").toString());
            String productName = jsonData.getString("productName");
            String phone = jsonData.getString("phone");
            Integer payType = jsonData.getInteger("payType");
            String date = jsonData.getString("date");
            Integer state = jsonData.getInteger("state");
            Integer page = jsonData.getInteger("page");
            Integer id = jsonData.getInteger("id");

            // if(!StringUtils.isEmpty(id)){
            // ShopProduct productDetailById =
            // shopProductService.getProductDetailById(Integer.valueOf(id));
            // shopProductService.formatProductLimit(productDetailById.getShopProductLimit());
            // jsonMap.put(RETURN_FLAG, true);
            // jsonMap.put("shopProducts", productDetailById);
            // return;
            // }

            if (id == null && page == null) {
                throw new Exception("未获取到页数！");
            }

            List<ShopTransOrder> list = shopOrderService.list(productName, phone, payType, date, state, page, id);
            if (!CollectionUtils.isEmpty(list)) {
                long now = System.currentTimeMillis();
                for (ShopTransOrder order : list) {
                    if (order.getState() == 1 && now - order.getUpdatedAt().getTime() > TIME_15_MINUTE) {
                        order.setState((short) 5);
                    }
                }
            }
            jsonMap.put("list", list);
            if (page != null) {
                Integer listCnt = shopOrderService.listCnt(productName, phone, payType, date, state);
                jsonMap.put("cnt", listCnt);
            }

            jsonMap.put(RETURN_FLAG, true);
        } catch (Exception e) {
            jsonMap.put(RETURN_FLAG, false);
            jsonMap.put(RETURN_MSG, e.getMessage());
            logger.error(e.getMessage(), e);
        } finally {
            response.getWriter().println(toJsonStr(jsonMap));
            response.flushBuffer();
        }

    }
}
